package com.huanbao.controller;


import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huanbao.base.dto.LoginDto;
import com.huanbao.base.lang.Result;
import com.huanbao.entity.PersonalIntegralNumber;
import com.huanbao.entity.User;
import com.huanbao.service.PersonalIntegralNumberService;
import com.huanbao.service.UserService;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Random;

/**
 * <p>
 * 环宝用户表 前端控制器
 * </p>
 *
 * @author zq
 * @since 2021-04-01
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserController {

    private final UserService userService;

    private final PersonalIntegralNumberService integralNumberService;

    @PostMapping("/save")
    public Result save(@Validated @RequestBody LoginDto loginDto) {
        User user = new User();
        if (null != userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()))) {
            return Result.fail("账户已存在,注册失败！");
        }
        //判断数据库中是否存在该账户
        boolean isEmpty = false;
        while (!isEmpty) {
            //定义变长字符串
            StringBuilder str = new StringBuilder();
            Random random = new Random();
            for (int i = 0; i < 8; i++) {
                str.append(random.nextInt(10));
            }
            long account = Long.parseLong(str.toString());
            if (null == userService.findAccount(account)) {
                user.setAccount(account);
                isEmpty = true;
            }
        }
        user.setUsername(loginDto.getUsername());
        user.setPassword(SecureUtil.md5(loginDto.getPassword()));
        boolean save = userService.save(user);
        User username = userService.getOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        PersonalIntegralNumber personalIntegralNumber = new PersonalIntegralNumber();
        personalIntegralNumber.setUserId(username.getId())
                .setIntegralNumber(0)
                .setUsername(user.getUsername());
        integralNumberService.save(personalIntegralNumber);
        if (save) {
            return Result.success(true);
        } else {
            return Result.fail("系统繁忙，请重新注册！");
        }
    }

    /**
     * 管理者通过搜索获得某一用户信息
     *
     * @param name
     * @return one
     */
    @RequiresAuthentication
    @GetMapping("/findOne")
    public Result findOne(String name) {
        User one = userService.getOne(new QueryWrapper<User>().eq("name", name));
        return Result.success(one);
    }

}
